<template>
	<!-- 完善用户信息 -->
	<uni-popup ref="userInfo" type="center">
		<view class="head-box">
			<view class="text">完善用户信息</view>
			<button open-type="chooseAvatar" @chooseavatar='chooseAvatar'>
				<image class="avatar" :src="avatar || '/static/images/default_avatar.png'" mode="aspectFill"></image>
			</button>
			<view class="contnet">
				<view class="name">昵称</view>
				<input type="nickname" placeholder="请输入昵称" v-model="nickName">
			</view>
			<view class="pop-text">
				<view class="text-one" @click="cancelUser()">取消</view>
				<view class="text-two" @click="confirmUser()">完成</view>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	import {
		uploadFile,
		registered,
		getUserInfo
	} from '@/apis/request.js';

	export default {
		name: "improve-user-info",
		data() {
			return {
				avatar: '',
				nickName: ''
			};
		},
		methods: {
			open() {
				this.$refs.userInfo.open();
			},
			close() {
				this.$emit('close');
				this.$refs.userInfo.close();
			},
			async chooseAvatar(e) {
				this.avatar = await uploadFile(e.detail.avatarUrl);
			},
			//修改用户信息
			confirmUser() {
				if (!this.avatar) {
					this.$Toast('请选择头像');
					return;
				}
				if (!this.nickName) {
					this.$Toast('请输入昵称');
					return;
				}
				this.registerUser({
					avatar: this.avatar,
					name: this.nickName,
					nickName: this.nickName
				});
			},
			cancelUser() {
				const randomName = '用户' + Math.random().toString(36).substring(2).toUpperCase();
				this.registerUser({
					avatar: '',
					name: randomName,
					nickName: randomName
				});
			},
			registerUser(params) {
				const id = uni.getStorageSync('userInfo').id;
				const inviteCode = uni.getStorageSync('inviteCode');
				registered(Object.assign({
					id: id,
					sex: 1,
					invitationCode: inviteCode
				}, params)).then((res) => {
					uni.removeStorageSync('inviteCode');
					this.close();
				}).catch(err => {
					this.$Toast(err.message || '请求失败，请重试！');
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.head-box {
		width: 500rpx;
		background-color: #fff;
		border-radius: 20rpx;

		.text {
			padding: 30rpx 0;
			text-align: center;
		}

		.avatar {
			width: 150rpx;
			height: 150rpx;
		}

		button {
			padding: 0;
			width: 150rpx;
			height: 150rpx;
		}

		.contnet {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 50rpx 30rpx;

			.name {
				flex-shrink: 0;
				padding-left: 20rpx;
			}

			input {
				flex: 1;
				padding-left: 20rpx;
				margin-left: 20rpx;
				border-bottom: 1rpx solid #F5F7F8;
			}
		}

		.pop-text {
			display: flex;
			justify-content: center;
			height: 79rpx;
			line-height: 79rpx;
			text-align: center;
			font-size: 32rpx;
			border-top: 1rpx solid #F5F7F8;

			.text-one {
				flex: 1;
				color: #BBBBBB;
				border-right: 1rpx solid #F5F7F8;
			}

			.text-two {
				flex: 1;
				color: $uni-color-primary;
				font-weight: bold;
			}
		}
	}
</style>